package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {
    public static void main(String[] args) {
        //获取对象Class类的三种方式
        User user = new User();
        Class<? extends User> clazz1 = user.getClass();
        Class<User> clazz2 = User.class;
        Class<?> clazz3 = null;
        try {
            clazz3 = Class.forName("reflection.User");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        System.out.println(clazz1+ "\n"+clazz2+ "\n"+clazz3+ "\n-------------------------------------------");
        try {
            Constructor<? extends User> constructor = clazz1.getConstructor(String.class, int.class);
            User newUser = constructor.newInstance("张三",16);
            System.out.println(newUser);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("-------------------------------------------");
        try {
            Field name = clazz1.getDeclaredField("name");
            name.setAccessible(true);
            name.set(user,"张三");
            Object o = name.get(user);
            System.out.println(o);
            System.out.println(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("-------------------------------------------");
        try {
            Method method = clazz1.getMethod("student");
            method.invoke(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
